/********************************************//**
 *  @files server.cpp
 *
 *  Implementa las funciones conectar y aceptar
 *  que permitirán la conexión con los clientes
 *  
 ***********************************************/

#include<iostream>
#include "server.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <netinet/in.h>
#include "TCP.h"
#include "sockets_.h"

using namespace std;

Server::Server()
{
}

void Server::conectar(const char* puerto[]){

    int fd, port;
    struct sockaddr_in serv_addr;

    fd=socket(AF_INET, SOCK_STREAM, 0);
    socket_server.setFileDescriptor(fd);

    if (fd < 0)
       perror("ERROR opening socket");

    bzero((char *) &serv_addr, sizeof(serv_addr));
    port = atoi(puerto[1]);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    serv_addr.sin_port = htons(port);


    if (bind(fd, (struct sockaddr *) &serv_addr,
             sizeof(serv_addr)) < 0)
             perror("ERROR on binding");

    listen(fd,10);

}

int Server::aceptar(){

    int newfd, clilength, pid;
    struct sockaddr cli_addr;
    TCP newsocket_server;

    clilength = sizeof(cli_addr);

    while (1) {

        newfd = accept(socket_server.getFileDescriptor(),
                       (sockaddr*) &cli_addr, (socklen_t*) &clilength);

        newsocket_server.setFileDescriptor(newfd);

        if (newfd < 0)
            perror("ERROR on accept");

        pid = fork();

        cout<<"Conectado correctamente"<<endl;

        if (pid < 0)
            perror("ERROR on fork");

        if (pid == 0)  {

            close(socket_server.getFileDescriptor());

            while(1){

                newsocket_server.recibir();
		
		cout<<"Mensaje recibido"<<endl;
		
                //newsocket_server.enviar();
            }

            exit(0);
        }

        else close(newsocket_server.getFileDescriptor());

    }

}

